package com.snopy.utils;

import com.snopy.leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;


/**
 * @author snopy
 * @description:
 * @classname DataFactoryUtil
 * @date 2021/02/04 9:03
 * @email 77912204@qq.com
 */
public class DataFactoryUtil {

    /**
     * @Description
     *
     * 默认空节点的子节点在数组中以null存在

     * @param arrs:
     * @return: com.snopy.leetcode.TreeNode
     * @Date 2022-03-17
     * @Author txl77912204@gmail.com
     **/
    public static TreeNode buildTree(Integer[] arrs){

        if (arrs==null || arrs.length==0){
            return null;
        }
        TreeNode root = new TreeNode(arrs[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int i = 0;
        while (!queue.isEmpty()){
            int len = queue.size();
            for (int k = 0;k < len;k++) {
                TreeNode node = queue.poll();
                if(i== arrs.length-1){
                    break;
                }
                if (arrs[++i] != null ) {
                    node.left = new TreeNode(arrs[i]);
                    queue.add(node.left);
                }
                if(i== arrs.length-1){
                    break;
                }
                if (arrs[++i] != null) {
                    node.right = new TreeNode(arrs[i]);
                    queue.add(node.right);
                }
            }

        }
        return root;
    }

    public static void main(String[] args) {
        Integer[] trees = new Integer[]{3,9,20,null,null,15,7};

        TreeNode root = buildTree(trees);
        System.out.println(traver(root));
    }
    public static String traver(TreeNode root){
        if (root==null){
            return "null";
        }
        return "TreeNode{val="+root.val+",left="+traver(root.left)+",right="+traver(root.right)+'}';
    }
}
